import time
from datetime import datetime, timedelta

from flask import current_app, jsonify
from flask import g
from flask import json
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import constants
from info.models import User, News
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import admin_blu

@admin_blu.route('/news_review')
def news_review():
    page = request.args.get("p", 1)
    keywords= request.args.get('keywords',None)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    current_page = 1
    total_page = 1
    filters = [News.status != 0]

    if keywords:
        # 如果关键字存在，就添加关键字搜索
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters) \
            .order_by(News.create_time.desc()) \
            .paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)

        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())
    data = {
        "current_page": current_app,
        "total_page": total_page,
        "news_list": news_dict_list
    }
    return render_template('admin/news_review.html',data=data)

@admin_blu.route('/user_list')
def user_list():
    # 从url中获取当前页数
    p = request.args.get("p",1)

    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)

    current_page = 1
    total_page = 1
    page_list = []

    # 查询数据
    try:
        paginates = User.query.filter(User.is_admin==False).paginate(p,constants.USER_COLLECTION_MAX_NEWS,False)

        current_page = paginates.page
        total_page = paginates.pages
        # 每页的数据,列表
        page_list = paginates.items
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='数据库查询错误')
    # 将模型转换为字典列表
    user_list = []
    for user in page_list:
        user_list.append(user.to_dict())

    data = {
        "current_page":current_page,
        "total_page":total_page,
        "users":user_list
    }
    return render_template('admin/user_list.html',data=data)

@admin_blu.route('/user_count')
def user_count():
    # 查询所用用户
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin==False).count()
    except Exception as e:
        current_app.logger.error(e)
    # 查询月增人数
    mon_count = 0
    try:
        now = time.localtime()
        mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        mon_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)
    # 查询日增人数
    day_count = 0
    try:
        day_begin = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
        day_begin_date = datetime.strptime(day_begin, '%Y-%m-%d')
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 获取活跃日期和活跃人数
    now_date = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')
    active_date = []
    active_count = []

    # 依次添加数据，再反转
    for i in range(0, 31):
        begin_date = now_date - timedelta(days=i)
        end_date = now_date - timedelta(days=(i - 1))
        active_date.append(begin_date.strftime('%Y-%m-%d'))
        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
                                      User.last_login < end_date).count()
        except Exception as e:
            current_app.logger.error(e)
        active_count.append(count)

    active_date.reverse()
    active_count.reverse()

    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_date": active_date,
        "active_count": active_count
    }

    # 折线数据分析


    return render_template('admin/user_count.html',data=data)


@admin_blu.route('/index')
@user_login_data
def admin_index():
    user = g.user
    return render_template('admin/index.html', user=user.to_dict())

@admin_blu.route('/login',methods=["POST","GET"])
def login():
    if request.method == 'GET':
        user_id = session.get('user_id', False)
        is_admin = session.get('is_admin', False)
        if user_id and is_admin:
            return render_template('admin/login.html')
    # 获取参数
    username = request.form.get("username")
    password = request.form.get("password")
    # 判断参数
    if not all([username, password]):
        return render_template('admin/login.html',errmsg='参数错误')

    # 查询当前用户
    try:
        user = User.query.filter(User.mobile == username, User.is_admin==True).first()
    except Exception as e:
        return render_template('admin/login.html',errmsg='查询失败')
    # 判断用户是否存在
    if not user:
        return render_template('admin/login.html',errmsg='用户不存在')

    if not user.check_passowrd(password):
        return render_template('admin/login.html',errmsg='密码错误')

    # 保存用户信息
    session['user_id'] = user.id
    session['mobile'] = user.mobile
    session['nick_name'] = user.nick_name
    session['is_admin'] = user.is_admin

    return redirect(url_for('admin.admin_index'))